package com.pxl.bi.bizmq;

import com.pxl.bi.common.ErrorCode;
import com.pxl.bi.exception.BusinessException;
import com.pxl.bi.manager.AIManager;
import com.pxl.bi.model.entity.Chart;
import com.pxl.bi.model.enums.ChartStatusEnum;
import com.pxl.bi.service.ChartService;
import com.rabbitmq.client.Channel;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

import static com.pxl.bi.common.BiMqConstant.*;

@Component
@Slf4j
public class DlxDirectConsumer {
    @Resource
    private ChartService chartService;
    @Resource
    private AIManager aiManager;

    @SneakyThrows
    @RabbitListener(queues = {DLX_QUEUE_NAME} ,ackMode = "MANUAL")
    public void receiveDLXMessage(String message, Channel channel, @Header(AmqpHeaders.DELIVERY_TAG) long deliveryTag) {
        log.info("死信 收到了处理不了的图表ID：{}",message);
        if (StringUtils.isBlank(message)){
            channel.basicReject(deliveryTag,false);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR,"消息为空");
        }
        long chartId = Long.parseLong(message);
        Chart chart = chartService.getById(chartId);
        if (chart == null) {
            // 如果图表为空，拒绝消息并抛出业务异常
            channel.basicNack(deliveryTag, false, false);
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "图表为空");
        }
        chart.setChartData(chartService.getChartDataById(chartId));
        if (StringUtils.isNotBlank(chart.getExecMessage()) && chart.getExecMessage().equals("数据量过大")){
            //数据量过大，无法进行再次处理，直接返回
            log.info("数据量过大，无法处理...");
            channel.basicReject(deliveryTag,false);
            return;
        }

        Chart updateChart = new Chart();
        updateChart.setId(chart.getId());
        updateChart.setStatus(ChartStatusEnum.DOING.getValue());
        boolean b = chartService.updateById(updateChart);
        if (!b) {
            // 如果更新图表执行中状态失败，拒绝消息并处理图表更新错误;重新放回队列
            channel.basicNack(deliveryTag, false, true);
            chartService.handleChartUpdateError(chart.getId(), "更新图表执行中状态失败");
            return;
        }

        //用户生成的信息
        String userInput = buildUserInput(chart);
        //调用AI
        String result = null;
        try {
            result = aiManager.sendMessageToAI(userInput);
        }catch (Exception e){
            channel.basicReject(deliveryTag, false);
            chartService.handleChartUpdateError(chart.getId(), "数据量过大");
            return;
        }
        // 对返回结果做拆分,按照4个中括号进行拆分
        String[] splits = result.split("///");
        // 拆分之后还要进行校验
        if (splits.length != 3) {
            //AI生成错误，重新放回队列中
            channel.basicNack(deliveryTag, false , true);
            chartService.handleChartUpdateError(chart.getId(), "AI 生成错误");
            return;
        }
        String genChart = splits[1].trim();
        String genResult = splits[2].trim();
        chart.setGenChart(genChart);
        chart.setGenResult(genResult);
        chart.setStatus(ChartStatusEnum.SUCCEED.getValue());
        chart.setExecMessage("");

        b = chartService.updateById(chart);
//        b &=  chartService.addChartData(chart);
        if (!b){
            chartService.handleChartUpdateError(chart.getId(), "更新图表成功状态失败");
            throw new BusinessException(ErrorCode.SYSTEM_ERROR,"图表保存失败");
        }
        channel.basicAck(deliveryTag,false);
    }
    /**
     * 构建用户输入
     * @param chart 图表对象
     * @return 用户输入字符串
     */
    private String buildUserInput(Chart chart) {
        // 获取图表的目标、类型和数据
        String goal = chart.getGoal();
        String chartType = chart.getChartType();
        String csvData = chart.getChartData();

        // 构造用户输入
        StringBuilder userInput = new StringBuilder();
        userInput.append("分析需求：").append("\n");

        // 拼接分析目标
        String userGoal = goal;
        if (com.alibaba.excel.util.StringUtils.isNotBlank(chartType)) {
            userGoal += "，请使用" + chartType;
        }
        userInput.append(userGoal).append("\n");
        userInput.append("原始数据：").append("\n");
        userInput.append(csvData).append("\n");
        // 将StringBuilder转换为String并返回
        return userInput.toString();
    }


}